/**
 * 服务模块统一导出文件
 * 集中管理和导出所有后端服务类
 */

/**
 * 服务接口定义，所有服务类应实现此接口
 */
export interface IService {
  /**
   * 初始化服务
   * @returns Promise<void>
   */
  initialize(): Promise<void>;
  
  /**
   * 获取服务名称
   * @returns string 服务名称
   */
  getName(): string;
}

// 安全地导入和导出服务类
export * from './calculation/rainfallService';
export * from './calculation/caveService';
export * from './calculation/stratumService';
export * from './calculation/crossingService';
export * from './testService';
export * from './historyService';
export * from './regulationService';
export * from './regulationIpcService';
export * from './fileOperationIpcService';
export * from './utilityIpcService';

/**
 * 服务注册表类型，使用更安全的类型定义
 */
export type ServiceClassType = new () => IService;

/**
 * 服务注册表接口
 */
export interface ServiceMap {
  [key: string]: ServiceClassType | undefined;
}

/**
 * 服务注册表，使用延迟加载方式避免类型错误
 */
export const serviceRegistry: ServiceMap = {};

/**
 * 动态注册服务
 * @param serviceName 服务名称
 * @param serviceClass 服务类
 */
export function registerService(serviceName: string, serviceClass: ServiceClassType): void {
  if (serviceName && serviceClass && typeof serviceClass === 'function') {
    serviceRegistry[serviceName] = serviceClass;
  }
}

/**
 * 根据服务名称获取服务类
 * @param serviceName 服务名称
 * @returns 服务类构造函数或undefined
 */
export function getServiceClass(serviceName: string): ServiceClassType | undefined {
  if (!serviceName || typeof serviceName !== 'string') {
    console.error('获取服务类失败: 服务名称必须是字符串');
    return undefined;
  }
  
  return serviceRegistry[serviceName];
}

/**
 * 初始化服务注册表
 * 采用延迟加载方式避免循环依赖和类型错误
 */
export function initializeServiceRegistry(): void {
  try {
    // 尝试导入并注册服务类，使用try-catch避免某个服务导入失败影响整体
    
    // 注册RainfallService
    try {
      const { RainfallService } = require('./rainfallService');
      if (RainfallService && typeof RainfallService === 'function') {
        registerService('rainfall', RainfallService);
      }
    } catch (error) {
      console.warn('未能加载RainfallService:', error);
    }
    
    // 注册CaveService
    try {
      const { CaveService } = require('./caveService');
      if (CaveService && typeof CaveService === 'function') {
        registerService('cave', CaveService);
      }
    } catch (error) {
      console.warn('未能加载CaveService:', error);
    }
    
    // 注册StratumService
    try {
      const { StratumService } = require('./stratumService');
      if (StratumService && typeof StratumService === 'function') {
        registerService('stratum', StratumService);
      }
    } catch (error) {
      console.warn('未能加载StratumService:', error);
    }
    
    // 注册CrossingService
    try {
      const { CrossingService } = require('./crossingService');
      if (CrossingService && typeof CrossingService === 'function') {
        registerService('crossing', CrossingService);
      }
    } catch (error) {
      console.warn('未能加载CrossingService:', error);
    }
    
    // 注册TestService
    try {
      const { TestService } = require('./testService');
      if (TestService && typeof TestService === 'function') {
        registerService('test', TestService);
      }
    } catch (error) {
      console.warn('未能加载TestService:', error);
    }
    
    // 注册HistoryService
    try {
      const { HistoryService } = require('./historyService');
      if (HistoryService && typeof HistoryService === 'function') {
        registerService('history', HistoryService);
      }
    } catch (error) {
      console.warn('未能加载HistoryService:', error);
    }
    
    // 注册RegulationService
    try {
      const { RegulationService } = require('./regulationService');
      if (RegulationService && typeof RegulationService === 'function') {
        registerService('regulation', RegulationService);
      }
    } catch (error) {
      console.warn('未能加载RegulationService:', error);
    }
    
    // 注册ExportCsvService
    try {
      const { ExportCsvService } = require('./exportCsvService');
      if (ExportCsvService && typeof ExportCsvService === 'function') {
        registerService('export-csv', ExportCsvService);
      }
    } catch (error) {
      console.warn('未能加载ExportCsvService:', error);
    }
    
    // 注册ExportExcelService
    try {
      const { ExportExcelService } = require('./exportExcelService');
      if (ExportExcelService && typeof ExportExcelService === 'function') {
        registerService('export-excel', ExportExcelService);
      }
    } catch (error) {
      console.warn('未能加载ExportExcelService:', error);
    }
    
    // 尝试注册TunnelService，但不强制要求
    try {
      const tunnelModule = require('./tunnelService');
      if (tunnelModule && typeof tunnelModule.default === 'function') {
        registerService('tunnel', tunnelModule.default);
      } else if (tunnelModule && typeof tunnelModule.TunnelService === 'function') {
        registerService('tunnel', tunnelModule.TunnelService);
      }
    } catch (error) {
      console.warn('未能加载TunnelService，该服务可能尚未实现:', error);
    }
    
    console.log('服务注册表初始化完成');
  } catch (error) {
    console.error('服务注册表初始化失败:', error);
  }
}

/**
 * 初始化所有服务
 * @returns Promise<boolean> 初始化是否成功
 */
export async function initializeAllServices(): Promise<boolean> {
  try {
    // 确保服务注册表已初始化
    if (Object.keys(serviceRegistry).length === 0) {
      initializeServiceRegistry();
    }
    
    const initializationPromises = Object.entries(serviceRegistry).map(async ([name, ServiceClass]) => {
      try {
        if (ServiceClass && typeof ServiceClass === 'function') {
          const service = new ServiceClass();
          if (service.initialize && typeof service.initialize === 'function') {
            await service.initialize();
            console.log(`服务初始化成功: ${name}`);
            return true;
          } else {
            console.warn(`服务 ${name} 缺少必要的方法，跳过初始化`);
            return false;
          }
        }
        return false;
      } catch (error) {
        console.error(`服务初始化失败 [${name}]:`, error);
        return false;
      }
    });
    
    const results = await Promise.all(initializationPromises);
    const successCount = results.filter(result => result).length;
    const totalCount = results.length;
    
    console.log(`服务初始化完成: 成功 ${successCount}/${totalCount}`);
    return successCount > 0;
  } catch (error) {
    console.error('初始化服务失败:', error);
    return false;
  }
}

// 导出常用服务类型作为类型别名，方便使用
export type {
  ServiceClassType as IServiceClass,
  ServiceMap as IServiceMap
};